import { createRouter, createWebHistory } from 'vue-router';
import { isAuthenticated } from '@/utils/auth';
import Index from '../views/Index.vue';
import Home from '../views/Home.vue';

const routes = [
  {
    path: '/',
    name: 'index',
    component: Index,
    children: [
      {
        path: '/',
        name: 'home',
        meta: {
          menu: true,
          title: '首页',
          requiresAuth: false,
        },
        component: Home,
      },
      {
        path: '/article/:articleId',
        name: 'article',
        meta: {
          menu: false,
          title: '文章',
          requiresAuth: false,
        },
        component: () => import('../views/ArticleDetail.vue'),
      },
      {
        path: '/timeline',
        name: 'timeline',
        meta: {
          menu: true,
          title: '时间线',
          requiresAuth: false,
        },
        component: () => import('../views/TimeLine.vue'),
      },
      {
        path: '/type/:articleTypeId',
        name: 'type',
        meta: {
          menu: false,
          title: '专栏',
          requiresAuth: false,
        },
        component: () => import('../views/ArticleType.vue')
      },
      {
        path: '/articleManage',
        name: 'articleManage',
        meta: {
          menu: true,
          title: '文章管理',
          requiresAuth: true,
        },
        component: () => import('../views/system/ArticleManage.vue')
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      menu: false,
      title: '登录',
      requiresAuth: false,
    },
    component: () => import('../views/Login.vue')
  },
  {
    path: '/notfound',
    name: '404',
    meta: {
      menu: false,
      title: '404',
      requiresAuth: false,
    },
    component: () => import('../views/404.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/notfound'
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
});

router.beforeEach((to, from, next) => {
  // 登录状态检查
  if (to.meta.requiresAuth && !isAuthenticated()) {
    return next('/login');
  }
  // 已登录用户访问 /login
  if (isAuthenticated() && to.path === '/login') {
    return next('/');
  }
  // 处理未匹配路由
  if (!to.matched.length) {
    return next('/notfound');
  }

  // 其他情况正常放行
  next();
});

export default router
